package com.caocao.interceptor;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;

/**
 * 描述:配置web中的信息,拦截的内容等
 *
 * @Author:操文健
 * @Create Time:2017-09-10 7:58
 */
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    /**
     * 重写该方法进行判断哪些URL进行拦截
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());

       // registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");

        // 自定义拦截内容的 拦截器需要拦截哪些内容和过滤哪些内容
       registry.addInterceptor(new AccountInterceptor())
               .addPathPatterns("/**")
               .excludePathPatterns("/login/**")
               .excludePathPatterns("/static/**")
               .excludePathPatterns("/");

        super.addInterceptors(registry);
    }

    /**
     * 实现父类方法,将springMvc默认的相关资源文件加手动添加
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 自定义将项目中classpath下的资源文件添加到系统中
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");

        super.addResourceHandlers(registry);
    }

    /**
     * 自动以手工配置主界面的跳转
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 设置默认的主界面进行映射到相关的index中
        //registry.addViewController("/").setViewName("forward:/static/login.html");
        registry.addViewController("/").setViewName("redirect:/static/login.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}
